package com.anlu.cloud.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anlu.cloud.user.LoginAppUser;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Map;

public class AppUserUtils {

    /**
     * 从spring secrity中获取登录用户信息
     * @return
     */
    public static LoginAppUser getLoginAppUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof OAuth2Authentication){
            OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication;
            authentication = oAuth2Auth.getUserAuthentication();

            if(authentication instanceof UsernamePasswordAuthenticationToken){
                UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
                //获取登录凭证
                Object principal = authentication.getPrincipal();
                if (principal instanceof LoginAppUser) {
                    return (LoginAppUser) principal;
                }

                Map map = (Map)authenticationToken.getDetails();
                map = (Map)map.get("principal");
                return JSONObject.parseObject(JSONObject.toJSONString(map), LoginAppUser.class);
            }

        }
        return null;
    }
}
